/**
 * 日志配置管理
 */

import { LOG_LEVELS } from './logger.js'

/**
 * 默认日志配置
 */
export const DEFAULT_LOG_CONFIG = {
  // 日志级别配置
  level: {
    development: LOG_LEVELS.DEBUG,
    production: LOG_LEVELS.ERROR,
    test: LOG_LEVELS.WARN
  },
  
  // 控制台输出配置
  console: {
    development: true,
    production: false,
    test: false
  },
  
  // 远程日志配置
  remote: {
    development: false,
    production: true,
    test: false
  },
  
  // 日志缓存配置
  cache: {
    maxLogs: 1000,
    maxSize: 5 * 1024 * 1024 // 5MB
  },
  
  // 性能日志配置
  performance: {
    slowThreshold: 1000, // 慢操作阈值(ms)
    enabled: true
  },
  
  // API日志配置
  api: {
    logRequests: true,
    logResponses: false, // 只在错误时记录响应
    logHeaders: false,
    sensitiveFields: ['password', 'token', 'secret', 'key'] // 敏感字段过滤
  },
  
  // 用户操作日志配置
  userActions: {
    enabled: true,
    trackClicks: true,
    trackFormSubmits: true,
    trackNavigation: true
  }
}

/**
 * 获取当前环境的日志配置
 */
export function getLogConfig() {
  const env = import.meta.env.MODE || 'development'
  
  const config = {
    ...DEFAULT_LOG_CONFIG,
    currentEnv: env
  }
  
  // 应用环境特定配置
  Object.keys(config).forEach(key => {
    if (typeof config[key] === 'object' && config[key][env] !== undefined) {
      config[key] = config[key][env]
    }
  })
  
  return config
}

/**
 * 过滤敏感数据
 */
export function sanitizeData(data, sensitiveFields = DEFAULT_LOG_CONFIG.api.sensitiveFields) {
  if (!data || typeof data !== 'object') {
    return data
  }
  
  if (Array.isArray(data)) {
    return data.map(item => sanitizeData(item, sensitiveFields))
  }
  
  const sanitized = { ...data }
  
  sensitiveFields.forEach(field => {
    if (sanitized[field] !== undefined) {
      sanitized[field] = '***FILTERED***'
    }
  })
  
  // 递归处理嵌套对象
  Object.keys(sanitized).forEach(key => {
    if (typeof sanitized[key] === 'object' && sanitized[key] !== null) {
      sanitized[key] = sanitizeData(sanitized[key], sensitiveFields)
    }
  })
  
  return sanitized
}

/**
 * 日志级别名称映射
 */
export const LOG_LEVEL_NAMES = {
  [LOG_LEVELS.DEBUG]: 'DEBUG',
  [LOG_LEVELS.INFO]: 'INFO', 
  [LOG_LEVELS.WARN]: 'WARN',
  [LOG_LEVELS.ERROR]: 'ERROR',
  [LOG_LEVELS.NONE]: 'NONE'
}

/**
 * 检查是否应该记录特定级别的日志
 */
export function shouldLog(currentLevel, messageLevel) {
  return messageLevel >= currentLevel
}

export default getLogConfig()

